import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Tag,
  Typography,
  Row,
  Col,
  Statistic,
  Tabs,
  Tooltip,
  Badge,
  Switch
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  DownloadOutlined,
  FilterOutlined,
  BugOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined,
  UserOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { TabPane } = Tabs;

const LogManagement = () => {
  // 状态管理
  const [activeTab, setActiveTab] = useState('service');
  const [serviceLogs, setServiceLogs] = useState([]);
  const [userBehaviors, setUserBehaviors] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState(null);
  const [searchForm] = Form.useForm();
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [refreshInterval, setRefreshInterval] = useState(null);
  
  // 筛选条件
  const [serviceFilters, setServiceFilters] = useState({
    level: '',
    serviceName: '',
    keyword: '',
    dateRange: []
  });
  
  const [behaviorFilters, setBehaviorFilters] = useState({
    eventType: '',
    userId: '',
    keyword: '',
    dateRange: []
  });
  
  // 分页
  const [servicePagination, setServicePagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  
  const [behaviorPagination, setBehaviorPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  
  // 统计数据
  const [serviceStats, setServiceStats] = useState({
    totalLogs: 0,
    errorLogs: 0,
    warningLogs: 0,
    infoLogs: 0
  });
  
  const [behaviorStats, setBehaviorStats] = useState({
    totalEvents: 0,
    uniqueUsers: 0,
    pageViews: 0,
    buttonClicks: 0
  });

  // 日志级别配置
  const logLevels = [
    { label: 'ERROR', value: 'ERROR', color: 'red', icon: <CloseCircleOutlined /> },
    { label: 'WARN', value: 'WARN', color: 'orange', icon: <WarningOutlined /> },
    { label: 'INFO', value: 'INFO', color: 'blue', icon: <InfoCircleOutlined /> },
    { label: 'DEBUG', value: 'DEBUG', color: 'green', icon: <BugOutlined /> }
  ];

  // 事件类型配置
  const eventTypes = [
    { label: '页面访问', value: 'page_view', color: 'blue' },
    { label: '按钮点击', value: 'button_click', color: 'green' },
    { label: '表单提交', value: 'form_submit', color: 'orange' },
    { label: '滚动事件', value: 'scroll', color: 'purple' },
    { label: '自定义事件', value: 'custom', color: 'cyan' }
  ];

  // 组件挂载时加载数据
  useEffect(() => {
    loadData();
  }, [activeTab, serviceFilters, behaviorFilters]);

  // 自动刷新
  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(() => {
        loadData();
      }, 30000); // 30秒刷新一次
      setRefreshInterval(interval);
    } else {
      if (refreshInterval) {
        clearInterval(refreshInterval);
        setRefreshInterval(null);
      }
    }
    
    return () => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    };
  }, [autoRefresh]);

  // 加载数据
  const loadData = async () => {
    if (activeTab === 'service') {
      await loadServiceLogs();
    } else {
      await loadUserBehaviors();
    }
  };

  // 加载服务日志
  const loadServiceLogs = async (page = servicePagination.current, pageSize = servicePagination.pageSize) => {
    setLoading(true);
    try {
      const params = {
        page: page - 1,
        size: pageSize,
        ...serviceFilters
      };
      
      // 处理日期范围
      if (serviceFilters.dateRange && serviceFilters.dateRange.length === 2) {
        params.startTime = serviceFilters.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        params.endTime = serviceFilters.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
        delete params.dateRange;
      }
      
      const response = await apiClient.get('/admin/logs/service', { params });
      const { content, totalElements } = response.data.data;
      console.log('服务日志响应:', response.data);
      setServiceLogs(content || []);
      setServicePagination(prev => ({
        ...prev,
        current: page,
        total: totalElements || 0
      }));
      
      // 加载统计数据
      await loadServiceStats();
      
    } catch (error) {
      console.error('加载服务日志失败:', error);
      message.error('加载服务日志失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载用户行为日志
  const loadUserBehaviors = async (page = behaviorPagination.current, pageSize = behaviorPagination.pageSize) => {
    setLoading(true);
    try {
      const params = {
        page: page - 1,
        size: pageSize,
        ...behaviorFilters
      };
      
      // 处理日期范围
      if (behaviorFilters.dateRange && behaviorFilters.dateRange.length === 2) {
        params.startTime = behaviorFilters.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        params.endTime = behaviorFilters.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
        delete params.dateRange;
      }
      
      const response = await apiClient.get('/admin/logs/user-behavior', { params });
      const { content, totalElements } = response.data;
      
      setUserBehaviors(content || []);
      setBehaviorPagination(prev => ({
        ...prev,
        current: page,
        total: totalElements || 0
      }));
      
      // 加载统计数据
      await loadBehaviorStats();
      
    } catch (error) {
      console.error('加载用户行为日志失败:', error);
      message.error('加载用户行为日志失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载服务日志统计
  const loadServiceStats = async () => {
    try {
      const response = await apiClient.get('/admin/logs/service/stats');
      setServiceStats(response.data.data.content || {});
    } catch (error) {
      console.error('加载服务日志统计失败:', error);
    }
  };

  // 加载用户行为统计
  const loadBehaviorStats = async () => {
    try {
      const response = await apiClient.get('/admin/logs/user-behavior/stats');
      setBehaviorStats(response.data || {});
    } catch (error) {
      console.error('加载用户行为统计失败:', error);
    }
  };

  // 搜索处理
  const handleSearch = (values) => {
    if (activeTab === 'service') {
      setServiceFilters({
        ...serviceFilters,
        ...values
      });
      setServicePagination(prev => ({ ...prev, current: 1 }));
    } else {
      setBehaviorFilters({
        ...behaviorFilters,
        ...values
      });
      setBehaviorPagination(prev => ({ ...prev, current: 1 }));
    }
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    if (activeTab === 'service') {
      setServiceFilters({
        level: '',
        serviceName: '',
        keyword: '',
        dateRange: []
      });
      setServicePagination(prev => ({ ...prev, current: 1 }));
    } else {
      setBehaviorFilters({
        eventType: '',
        userId: '',
        keyword: '',
        dateRange: []
      });
      setBehaviorPagination(prev => ({ ...prev, current: 1 }));
    }
  };

  // 查看详情
  const handleViewDetail = (record) => {
    setSelectedLog(record);
    setDetailModalVisible(true);
  };

  // 服务日志表格列
  const serviceColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
      sorter: true
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => {
        const config = logLevels.find(l => l.value === level);
        return (
          <Tag color={config?.color} icon={config?.icon}>
            {level}
          </Tag>
        );
      },
      filters: logLevels.map(l => ({ text: l.label, value: l.value })),
      onFilter: (value, record) => record.level === value
    },
    {
      title: '服务名',
      dataIndex: 'serviceName',
      key: 'serviceName',
      width: 120,
      ellipsis: true
    },
    {
      title: '类名',
      dataIndex: 'className',
      key: 'className',
      width: 200,
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <Text code>{text?.split('.').pop()}</Text>
        </Tooltip>
      )
    },
    {
      title: '方法名',
      dataIndex: 'methodName',
      key: 'methodName',
      width: 120,
      ellipsis: true
    },
    {
      title: '日志内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <Text>{text}</Text>
        </Tooltip>
      )
    },
    {
      title: 'TraceID',
      dataIndex: 'traceId',
      key: 'traceId',
      width: 120,
      ellipsis: true,
      render: (text) => text && (
        <Text code copyable={{ text }}>
          {text.substring(0, 8)}...
        </Text>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      )
    }
  ];

  // 用户行为表格列
  const behaviorColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
      sorter: true
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 120,
      ellipsis: true,
      render: (text) => text && (
        <Text code>{text}</Text>
      )
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      key: 'eventType',
      width: 120,
      render: (eventType) => {
        const config = eventTypes.find(e => e.value === eventType);
        return (
          <Tag color={config?.color}>
            {config?.label || eventType}
          </Tag>
        );
      },
      filters: eventTypes.map(e => ({ text: e.label, value: e.value })),
      onFilter: (value, record) => record.eventType === value
    },
    {
      title: '页面URL',
      dataIndex: 'pageUrl',
      key: 'pageUrl',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <Text>{text}</Text>
        </Tooltip>
      )
    },
    {
      title: '页面标题',
      dataIndex: 'pageTitle',
      key: 'pageTitle',
      width: 150,
      ellipsis: true
    },
    {
      title: '设备信息',
      dataIndex: 'deviceInfo',
      key: 'deviceInfo',
      width: 100,
      render: (text) => (
        <Tag color={text === 'Mobile' ? 'orange' : text === 'Tablet' ? 'blue' : 'green'}>
          {text}
        </Tag>
      )
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      )
    }
  ];

  // 搜索表单
  const renderSearchForm = () => {
    const isService = activeTab === 'service';
    
    return (
      <Card size="small" style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 0 }}
        >
          <Form.Item name="dateRange" label="时间范围">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          
          {isService ? (
            <>
              <Form.Item name="level" label="日志级别">
                <Select placeholder="选择级别" allowClear style={{ width: 120 }}>
                  {logLevels.map(level => (
                    <Option key={level.value} value={level.value}>
                      {level.icon} {level.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              
              <Form.Item name="serviceName" label="服务名">
                <Input placeholder="输入服务名" style={{ width: 150 }} />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item name="eventType" label="事件类型">
                <Select placeholder="选择事件类型" allowClear style={{ width: 150 }}>
                  {eventTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              
              <Form.Item name="userId" label="用户ID">
                <Input placeholder="输入用户ID" style={{ width: 150 }} />
              </Form.Item>
            </>
          )}
          
          <Form.Item name="keyword" label="关键词">
            <Input placeholder="输入关键词" style={{ width: 200 }} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset} icon={<FilterOutlined />}>
                重置
              </Button>
              <Button onClick={loadData} icon={<ReloadOutlined />}>
                刷新
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    );
  };

  // 统计卡片
  const renderStats = () => {
    const isService = activeTab === 'service';
    const stats = isService ? serviceStats : behaviorStats;
    
    if (isService) {
      return (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总日志数"
                value={stats.totalLogs}
                prefix={<FileTextOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="错误日志"
                value={stats.errorLogs}
                valueStyle={{ color: '#cf1322' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="警告日志"
                value={stats.warningLogs}
                valueStyle={{ color: '#fa8c16' }}
                prefix={<WarningOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="信息日志"
                value={stats.infoLogs}
                valueStyle={{ color: '#1890ff' }}
                prefix={<InfoCircleOutlined />}
              />
            </Card>
          </Col>
        </Row>
      );
    } else {
      return (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总事件数"
                value={stats.totalEvents}
                prefix={<FileTextOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="独立用户"
                value={stats.uniqueUsers}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="页面访问"
                value={stats.pageViews}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="按钮点击"
                value={stats.buttonClicks}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>
      );
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={2}>日志管理</Title>
        <Space>
          <span>自动刷新:</span>
          <Switch
            checked={autoRefresh}
            onChange={setAutoRefresh}
            checkedChildren="开"
            unCheckedChildren="关"
          />
        </Space>
      </div>
      
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane
          tab={
            <span>
              <FileTextOutlined />
              服务日志
            </span>
          }
          key="service"
        >
          {renderStats()}
          {renderSearchForm()}
          
          <Card>
            <Table
              columns={serviceColumns}
              dataSource={serviceLogs}
              rowKey="id"
              loading={loading}
              pagination={{
                ...servicePagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                onChange: (page, pageSize) => {
                  setServicePagination(prev => ({ ...prev, current: page, pageSize }));
                  loadServiceLogs(page, pageSize);
                }
              }}
              scroll={{ x: 1200 }}
              size="small"
            />
          </Card>
        </TabPane>
        
        <TabPane
          tab={
            <span>
              <UserOutlined />
              用户行为
            </span>
          }
          key="behavior"
        >
          {renderStats()}
          {renderSearchForm()}
          
          <Card>
            <Table
              columns={behaviorColumns}
              dataSource={userBehaviors}
              rowKey="id"
              loading={loading}
              pagination={{
                ...behaviorPagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                onChange: (page, pageSize) => {
                  setBehaviorPagination(prev => ({ ...prev, current: page, pageSize }));
                  loadUserBehaviors(page, pageSize);
                }
              }}
              scroll={{ x: 1200 }}
              size="small"
            />
          </Card>
        </TabPane>
      </Tabs>
      
      {/* 详情弹窗 */}
      <Modal
        title="日志详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedLog && (
          <div>
            <Title level={4}>基本信息</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Text strong>时间: </Text>
                <Text>{dayjs(selectedLog.timestamp).format('YYYY-MM-DD HH:mm:ss')}</Text>
              </Col>
              {activeTab === 'service' ? (
                <>
                  <Col span={12}>
                    <Text strong>级别: </Text>
                    <Tag color={logLevels.find(l => l.value === selectedLog.level)?.color}>
                      {selectedLog.level}
                    </Tag>
                  </Col>
                  <Col span={12}>
                    <Text strong>服务名: </Text>
                    <Text>{selectedLog.serviceName}</Text>
                  </Col>
                  <Col span={12}>
                    <Text strong>TraceID: </Text>
                    <Text code copyable={{ text: selectedLog.traceId }}>{selectedLog.traceId}</Text>
                  </Col>
                </>
              ) : (
                <>
                  <Col span={12}>
                    <Text strong>用户ID: </Text>
                    <Text code>{selectedLog.userId}</Text>
                  </Col>
                  <Col span={12}>
                    <Text strong>事件类型: </Text>
                    <Tag color={eventTypes.find(e => e.value === selectedLog.eventType)?.color}>
                      {eventTypes.find(e => e.value === selectedLog.eventType)?.label || selectedLog.eventType}
                    </Tag>
                  </Col>
                  <Col span={12}>
                    <Text strong>会话ID: </Text>
                    <Text code>{selectedLog.sessionId}</Text>
                  </Col>
                </>
              )}
            </Row>
            
            <Title level={4} style={{ marginTop: 16 }}>详细内容</Title>
            {activeTab === 'service' ? (
              <div>
                <p><Text strong>类名: </Text><Text code>{selectedLog.className}</Text></p>
                <p><Text strong>方法名: </Text><Text code>{selectedLog.methodName}</Text></p>
                <p><Text strong>日志内容: </Text></p>
                <TextArea value={selectedLog.content} rows={4} readOnly />
                {selectedLog.exceptionMessage && (
                  <div style={{ marginTop: 16 }}>
                    <p><Text strong>异常信息: </Text></p>
                    <TextArea value={selectedLog.exceptionMessage} rows={3} readOnly />
                  </div>
                )}
                {selectedLog.stackTrace && (
                  <div style={{ marginTop: 16 }}>
                    <p><Text strong>堆栈跟踪: </Text></p>
                    <TextArea value={selectedLog.stackTrace} rows={6} readOnly />
                  </div>
                )}
              </div>
            ) : (
              <div>
                <p><Text strong>页面URL: </Text><Text>{selectedLog.pageUrl}</Text></p>
                <p><Text strong>页面标题: </Text><Text>{selectedLog.pageTitle}</Text></p>
                <p><Text strong>设备信息: </Text><Text>{selectedLog.deviceInfo}</Text></p>
                <p><Text strong>浏览器: </Text><Text>{selectedLog.browserInfo}</Text></p>
                <p><Text strong>操作系统: </Text><Text>{selectedLog.osInfo}</Text></p>
                <p><Text strong>屏幕分辨率: </Text><Text>{selectedLog.screenResolution}</Text></p>
                {selectedLog.eventData && (
                  <div style={{ marginTop: 16 }}>
                    <p><Text strong>事件数据: </Text></p>
                    <TextArea value={selectedLog.eventData} rows={4} readOnly />
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default LogManagement;